// ActionScript file
//client section
import components.clPrintImeiList;
import components.clPrintPayment;
import components.clPrintPriceList;

import flash.display.DisplayObject;
import flash.events.DataEvent;
import flash.events.Event;
import flash.net.*;

import mx.collections.XMLListCollection;
import mx.controls.Alert;
import mx.controls.DataGrid;
import mx.controls.Text;
import mx.events.CloseEvent;
import mx.events.DataGridEvent;
import mx.events.IndexChangedEvent;
import mx.events.ValidationResultEvent;
import mx.printing.*;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.validators.EmailValidator;
import mx.validators.StringValidator;
import mx.validators.Validator;

import vclass.Vhttp;

 private var phones:XML;
 private var marcaList:XMLList;
 private var clNumRowsPriceList:Number = 0;
   
 [Bindable]
 private var marcaListCol:XMLListCollection;
 
 private var modelList:XMLList;
 
 [Bindable]
 private var modelListCol:XMLListCollection;
 
 private var companieList:XMLList;
 
 [Bindable]
 private var companieListCol:XMLListCollection;
 
 //pentru cod special
 [Bindable]
 public var codAlcatel:Boolean = false;

[Bindable]
public var codBruteForce:Boolean = false;

[Bindable]
public var codIphone:Boolean = false;

 //pentru validators
 [Bindable]
 public var formIsValid:Boolean = false;
 
 private var focussedFormControl:DisplayObject;
 
 private function clShowIndex(event:IndexChangedEvent):void{
	var index:Number = event.newIndex;
	switch(index)
	{
		case 1:
			clGetImei();
			break;
		case 2:
			clGetPriceList();
			break;
		case 3:
			clGetPersonalInfo();
			break;
		case 4:
			clGetPayment();
			break;
		default:
			return;
			break;
	}
}
private function validatePersonalForm(event:Event):void 
{                    
    focussedFormControl = event.target as DisplayObject;               
    formIsValid = true;            
    validate(emailValidator);                
    validate(passValidator);
}
private function validateImeiForm(event:Event):void 
{                    
    focussedFormControl = event.target as DisplayObject;               
    formIsValid = true;            
    validate(imeiValidator);                
}
private function validate(validator:Validator):Boolean
 {                
    // Get a reference to the component that is the
    // source of the validator.
     var validatorSource:DisplayObject = validator.source as DisplayObject;
    
    // Suppress events if the current control being validated is not
    // the currently focussed control on the form. This stops the user
    // from receiving visual validation cues on other form controls.
    var suppressEvents:Boolean = (validatorSource != focussedFormControl);
    
    // Carry out validation. Returns a ValidationResultEvent.
    // Passing null for the first parameter makes the validator 
    // use the property defined in the property tag of the
    // <mx:Validator> tag.
    var event:ValidationResultEvent = validator.validate(null, suppressEvents); 
                    
    // Check if validation passed and return a boolean value accordingly
     var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);
     
     // Update the formIsValid flag
    formIsValid = formIsValid && currentControlIsValid;
     
     return currentControlIsValid;
  }
 private function clGetPhones(myPrice:Text):void{
 	//init validators
 	//initValidators();
 	
 	var my:Vhttp = new Vhttp();
	my.target = null;
	my.request.sesiune = sesiune;
	my.request.op = "getPhones";
	my.url = domeniu+"client2.php";
	my.send();
	function initCampuri():void{
		//confirmareOp(my,false);
		if(alertErrorInvoked)return;
		phones = new XML(my.getXML);
		
		marcaList = phones.marca.@nume;
		marcaListCol = new XMLListCollection(marcaList);
		
		modelList = phones.marca[0].model.@nume;
		modelListCol = new XMLListCollection(modelList);
		
		companieList = phones.marca[0].model[0].companie.@nume;
		companieListCol = new XMLListCollection(companieList);
		
		myPrice.text = phones.marca[0].model[0].companie.@cost+" euro";
		
		my.removeEventListener(ResultEvent.RESULT,initCampuri);
		//check daca cere cod special. cere pentru ca este alcatel primul
		checkSpecialCode(clCbMarca.selectedLabel, clCbModel.selectedLabel, clCbCompanie.selectedLabel);
	}
	my.addEventListener(ResultEvent.RESULT,initCampuri);
 }
 private function preventEdit(event:DataGridEvent):void{
 		//event.preventDefault();//previne modificarea
 		clDgListImei.destroyItemEditor();
 		clDgListImei.dataProvider.notifyItemUpdate(clDgListImei.editedItemRenderer);
 }
 private function clGetImei(imei:String="0"):void{
 	var my:Vhttp = new Vhttp();
 	my.url = domeniu+"client2.php";
	my.target = clDgListImei;
	my.request.sesiune = sesiune;
	my.request.op = "getImeiList";
 	if(imei != "0"){
		my.request.imei = clSearchImei.text;
 	}
 	my.send();
 }
 private function clGetPersonalInfo():void{
	 	//initializare validatori
	 	var my:Vhttp = new Vhttp();
		my.target = null;
		my.request.sesiune = sesiune;
		my.request.op = "getPersonalInfo";
		my.url = domeniu+"client2.php";
		my.send();
		function init(event:ResultEvent):void{
			my.removeEventListener(ResultEvent.RESULT,init);
			if(alertErrorInvoked)return;
			var personal:XML;
			personal = new XML(my.getXML);
			
			clPassword.text = personal.row.@parola;
			clEmail.text = personal.row.@mail;
			clPhone.text = personal.row.@phone;
			clCreditTotal.text = personal.row.@total;
			clCreditConsumat.text = personal.row.@consumat;
			clCreditRamas.text = personal.row.@ramas;
			if(nume == 'test'){
				clPassword.editable = false;
				clEmail.editable = false;
				clPhone.editable = false;
			}else{
				clPassword.editable = true;
				clEmail.editable = true;
				clPhone.editable = true;
			}
			
		}
		my.addEventListener(ResultEvent.RESULT,init);
 }
 private function clGetPayment():void{
 		var my:Vhttp = new Vhttp();
		my.target = clDgPayment;
		my.request.sesiune = sesiune;
		my.request.op = "getPayment";
		my.url = domeniu+"client2.php";
		my.send();
 }
 private function clGetPriceList():void{
 	if(clDgPriceList.dataProvider == null){
 		var my:Vhttp = new Vhttp();
		my.target = clDgPriceList;
		my.request.sesiune = sesiune;
		my.request.op = "getPriceList";
		my.url = domeniu+"client2.php";
		my.send();
		function getRows():void{
			my.removeEventListener(ResultEvent.RESULT,getRows);
			if(alertErrorInvoked)return;
			for each (var num:Object in clDgPriceList.dataProvider){
				clNumRowsPriceList +=1;
			}
		}
		my.addEventListener(ResultEvent.RESULT,getRows);
	
 	}
 }
 private function clUpdatePersonal():void{
 	var my:Vhttp = new Vhttp();
	my.target = null;
	my.withConfirmare = true;
	my.request.sesiune = sesiune;
	my.request.op = "updatePersonalInfo";
	my.request.pass = clPassword.text;
	my.request.mail = clEmail.text;
	my.request.phone = clPhone.text;
	my.url = domeniu+"client2.php";
	my.send();
	function raspuns():void{
		my.removeEventListener(ResultEvent.RESULT,raspuns);					
	}
	my.addEventListener(ResultEvent.RESULT,raspuns);
 }
 private function clSendImei():void{
 	var my:Vhttp = new Vhttp();
	my.target = null;
	my.withConfirmare = true;
	my.request.sesiune = sesiune;
	my.request.op = "clSendImei";
	my.request.marca = clCbMarca.selectedLabel;
	my.request.model = clCbModel.selectedLabel;
	my.request.companie = clCbCompanie.selectedLabel;
	if(codAlcatel){
		if((clSpecialCodePart1.length == 5)&&(clSpecialCodePart2.length == 7)){
			my.request.specialCode = clSpecialCodePart1.text+"-"+clSpecialCodePart2.text;
		}else{
			Alert.show("Please insert special code for Alcatel phone!","Error");
			return;
		}
	}
	if(codBruteForce)
	{
		if(cbBox.selectedIndex == -1 || inHash.text == 'Enter hash code ...' || inHash.text.length < 10)
		{
			Alert.show("Please select unlock box and enter hash code for Nokia!");
			return;
		}else{
			my.request.specialCode = "BruteForce Code: box "+cbBox.selectedLabel+" hash code:"+inHash.text;
		}
	}
	if(codIphone)
	{
		if(clSpecialCodeIphone.length != 9)
		{
			Alert.show("Phone number required. Please insert one!!");
			clSpecialCodeIphone.setFocus();
			return;
		}else{
			my.request.specialCode = "Phone number for Iphone is: "+clSpecialCodeIphone.text;
		}
	}
	my.request.imei = clImei.text;
	my.url = domeniu+"client2.php";
	my.send();
	function raspuns():void{
		clImei.text = "";
		clSpecialCodePart1.text = "";
		clSpecialCodePart2.text = "";
		clImei.setFocus();
		my.removeEventListener(ResultEvent.RESULT,raspuns);					
	}
	my.addEventListener(ResultEvent.RESULT,raspuns);
	
}
//sectiune upload ######################################################## sectiune upload #####################################
 //fileref e definit la admin.as
 
 private function clselectHandler(event:Event):void{
 	clListImeiFileName.text = fileRef.name;
 	//pass parametri
 	var params:URLVariables = new URLVariables();
	params.sesiune = sesiune;
 	var request:URLRequest = new URLRequest(domeniu+"uploader2.php");
 	request.method = URLRequestMethod.POST;
	request.data = params;
      try {
         // upload file
          fileRef.upload(request);
      }
      catch (error:Error) {
          Alert.show("error"+error.message);
      }
     fileRef.removeEventListener(Event.SELECT,selectHandler);
 }
 private function cluploadCompleteHandler(event:DataEvent):void{
 	clListImeiFileName.text = "";
 	var hop:XML = new XML(event.data);
 	var myFlag:String = hop.attribute("flag");
 	var myCode:String = hop.attribute("rpc");
 	var messID:Number = hop.attribute("messid");
 	if(myFlag == "0"){
 		Alert.show(messages.row.(@id==messID).@continut+" RPC: "+myCode);
 	}else{
 		Alert.show("Operation succesfull!");
 	}
 	fileRef.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, cluploadCompleteHandler);
 }
  private function clUpload():void{
	var excelFilter:FileFilter = new FileFilter("Files (*.ask)", "*.ask");
	fileRef.addEventListener(Event.SELECT, clselectHandler);
	fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, cluploadCompleteHandler);
	//fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    try {
             var success:Boolean = fileRef.browse(new Array(excelFilter));
    }
    catch (error:Error) {
             Alert.show("Unable to browse for files.");
    }
 }
//  #################################################################### sectiune export ##########################################################
//functia decideDownload este definita in generalFunctions
private function clListImeiExport(searchImei:String=''):void{
	var loader:URLLoader = new URLLoader();
 	loader.dataFormat = URLLoaderDataFormat.VARIABLES;
 	var params:URLVariables = new URLVariables();
	params.sesiune = sesiune;
	params.op = "clGetImei";
	params.searchImei = searchImei;
	params.nume = nume;
 	var request:URLRequest = new URLRequest(domeniu+"export2.php");
 	request.method = URLRequestMethod.GET;
 	request.data = params;
 	loader.load(request);
 	//register listener
 	loader.addEventListener(Event.COMPLETE,decideDownload);
}
private function clPriceListExport():void{
	var loader:URLLoader = new URLLoader();
 	loader.dataFormat = URLLoaderDataFormat.VARIABLES;
 	var params:URLVariables = new URLVariables();
	params.sesiune = sesiune;
	params.op = "clGetPriceList";
	params.nume = nume;
 	var request:URLRequest = new URLRequest(domeniu+"export2.php");
 	request.method = URLRequestMethod.GET;
 	request.data = params;
 	loader.load(request);
 	//register listener
 	loader.addEventListener(Event.COMPLETE,decideDownload);
}
private function clPlatiExport():void{
	var loader:URLLoader = new URLLoader();
 	loader.dataFormat = URLLoaderDataFormat.VARIABLES;
 	var params:URLVariables = new URLVariables();
	params.sesiune = sesiune;
	params.op = "clGetPlati";
	params.nume = nume;
 	var request:URLRequest = new URLRequest(domeniu+"export2.php");
 	request.method = URLRequestMethod.GET;
 	request.data = params;
 	loader.load(request);
 	//register listener
 	loader.addEventListener(Event.COMPLETE,decideDownload);
}